import React, {useEffect, useState} from 'react';
import {useLocation, useNavigate} from 'react-router-dom';
import {
  Building2,
  Calendar,
  ChevronLeft,
  Heart,
  MapPin,
  Megaphone,
  PartyPopper,
  Snowflake,
  Sun,
  Target,
  Upload,
  Users,
  Zap
} from 'lucide-react';
import {Req, UploadFile} from '../../util/fetch';

interface Category {
  id: string;
  name: string;
  icon: React.ReactNode;
  color: string;
}

const categories: Category[] = [
  {
    id: 'dealer-meeting',
    name: '分销商会议',
    icon: <Building2 className="w-6 h-6" />,
    color: 'from-purple-500 to-purple-600'
  },
  {
    id: 'ice-sword',
    name: '寒冰亮剑',
    icon: <Snowflake className="w-6 h-6" />,
    color: 'from-cyan-500 to-cyan-600'
  },
  {
    id: 'customer-thanks',
    name: '客户答谢会',
    icon: <Heart className="w-6 h-6" />,
    color: 'from-pink-500 to-pink-600'
  },
  {
    id: 'new-year',
    name: '新春年会',
    icon: <PartyPopper className="w-6 h-6" />,
    color: 'from-red-500 to-red-600'
  },
  {
    id: 'spring-thunder',
    name: '春雷行动',
    icon: <Zap className="w-6 h-6" />,
    color: 'from-blue-500 to-blue-600'
  },
  {
    id: '520-roadshow',
    name: '520路演',
    icon: <Megaphone className="w-6 h-6" />,
    color: 'from-indigo-500 to-indigo-600'
  },
  {
    id: 'sunshine',
    name: '骄阳行动',
    icon: <Sun className="w-6 h-6" />,
    color: 'from-orange-500 to-orange-600'
  },
  {
    id: 'target-sprint',
    name: '目标冲刺动员',
    icon: <Target className="w-6 h-6" />,
    color: 'from-green-500 to-green-600'
  }
];

export default function AdminTrainings() {
  const navigate = useNavigate();
  const location = useLocation();
  const categoryId = new URLSearchParams(location.search).get('category');

  const [formData, setFormData] = useState({
    category: categoryId || '',
    title: '',
    subTitle: '',
    startDate: '',
    endDate: '',
    place: '',
    organizerId: '',
    organizerName: '',
    participants: 0,
    views: 0,
    status: '0',
    cover: '',
    tags: '',
    description: '',
  });

  const [userDropdown, setUserDropdown] = useState<any>([]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    // 这里处理表单提交逻辑
    console.log('Form submitted:', formData);
    const organizer = userDropdown.find(item => item.id === formData.organizerId)
    formData.organizerName = organizer?.name || ''
    const res = await Req('/bsTrain/add', {
      method: 'POST',
      body: formData,
      headers: undefined
    })
    if (res.success) {
      alert(res.message)
      navigate(-1);
    } else {
      alert(res.message)
    }

  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const queryUserList = async () => {
    const res = await Req(`/sysUser/list`)
    if (res.success) {
      setUserDropdown(res.data.map(item => {
        return {id: item.id, name: item.realname}
      }))
    } else {
      alert(res.message)
    }
  };

  useEffect(() => {
    queryUserList()
  }, [])

  const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files;
    if (!files) return;
    const res = await UploadFile(0, files[0])
    setFormData(prev => ({
      ...prev,
      'cover': res.data.url
    }));
    console.log('handleFileChange', files, res);
  };

  return (
    <div className="min-h-screen bg-gray-50 pb-12">
      {/* 头部 */}
      <div className="bg-white px-6 py-4 flex items-center justify-between shadow-sm">
        <div className="flex items-center">
          <button onClick={() => navigate(-1)} className="mr-4">
            <ChevronLeft className="w-6 h-6 text-gray-600" />
          </button>
          <h1 className="text-xl font-semibold">添加训练</h1>
        </div>
        <button
          onClick={handleSubmit}
          className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
        >
          保存
        </button>
      </div>

      {/* 表单内容 */}
      <div className="max-w-4xl mx-auto mt-8">
        <form onSubmit={handleSubmit} className="bg-white rounded-xl shadow-sm p-6 space-y-6">
          {/* 训练分类 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              训练分类 <span className="text-red-500">*</span>
            </label>
            <select
              name="category"
              value={formData.category}
              onChange={handleChange}
              className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
            >
              <option value="">请选择训练分类</option>
              {categories.map(category => (
                <option key={category.id} value={category.id}>
                  {category.name}
                </option>
              ))}
            </select>
          </div>

          {/* 训练名称 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              训练名称 <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              name="title"
              value={formData.title}
              onChange={handleChange}
              className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="请输入训练名称"
              required
            />
          </div>

          {/* 副标题 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              副标题
            </label>
            <input
              type="text"
              name="subTitle"
              value={formData.subTitle}
              onChange={handleChange}
              className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="请输入副标题"
            />
          </div>

          {/* 描述 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              描述
            </label>
            <textarea
              name="description"
              value={formData.description}
              onChange={handleChange}
              rows={4}
              className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="请输入训练描述"
            />
          </div>

          {/* 封面图 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              封面图
            </label>
            <div className="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-dashed rounded-lg">
              {formData.cover ?
                  (
                      <img src={formData.cover} alt="封面图" className="w-21 h-21 rounded-lg"/>)
                  : (
                      <div className="space-y-1 text-center">
                        <Upload className="mx-auto h-12 w-12 text-gray-400"/>
                        <div className="flex text-sm text-gray-600">
                          <label
                              htmlFor="cover-upload"
                              className="relative cursor-pointer rounded-md font-medium text-blue-600 hover:text-blue-500"
                          >
                            <span>点击此处选择要上传的图片</span>
                            <input
                                id="cover-upload"
                                name="coverImage"
                                type="file"
                                className="sr-only"
                                accept="image/*"
                                onChange={handleFileChange}
                            />
                          </label>
                          {/*<p className="pl-1">或拖拽图片到此处</p>*/}
                        </div>
                        <p className="text-xs text-gray-500">PNG, JPG, GIF 最大 10MB</p>
                      </div>)
              }
            </div>
          </div>

          {/* 日期选择 */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                开始日期 <span className="text-red-500">*</span>
              </label>
              <div className="relative">
                <Calendar className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                <input
                  type="date"
                  name="startDate"
                  value={formData.startDate}
                  onChange={handleChange}
                  className="w-full pl-10 pr-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  required
                />
              </div>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                结束日期 <span className="text-red-500">*</span>
              </label>
              <div className="relative">
                <Calendar className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                <input
                  type="date"
                  name="endDate"
                  value={formData.endDate}
                  onChange={handleChange}
                  className="w-full pl-10 pr-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  required
                />
              </div>
            </div>
          </div>

          {/* 组织者 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              组织者 <span className="text-red-500">*</span>
            </label>
            <div className="relative">
              {/*<User className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />*/}
              {/*<input*/}
              {/*  type="text"*/}
              {/*  name="organizer"*/}
              {/*  value={formData.organizer}*/}
              {/*  onChange={handleChange}*/}
              {/*  className="w-full pl-10 pr-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"*/}
              {/*  placeholder="请输入组织者姓名"*/}
              {/*  required*/}
              {/*/>*/}
              <select
                  name="organizerId"
                  defaultValue={formData.organizerId}
                  onChange={handleChange}
                  className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  required
              >
                {userDropdown.map(user => (
                    <option key={user.id} value={user.id}>
                      {user.name}
                    </option>
                ))}
              </select>
            </div>
          </div>

          {/* 参与人数 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              预计参与人数
            </label>
            <div className="relative">
              <Users className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5"/>
              <input
                  type="number"
                  name="participants"
                  value={formData.participants}
                  onChange={handleChange}
                  className="w-full pl-10 pr-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="请输入预计参与人数"
                min="0"
              />
            </div>
          </div>

          {/* 地点 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              地点 <span className="text-red-500">*</span>
            </label>
            <div className="relative">
              <MapPin className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
              <input
                type="text"
                name="place"
                value={formData.place}
                onChange={handleChange}
                className="w-full pl-10 pr-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="请输入活动地点"
                required
              />
            </div>
          </div>
        </form>
      </div>
    </div>
  );
}